<script setup lang="ts">
import { ref, watch, reactive, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { changePasswordApi } from '@/api/userManage/index'
import { ElMessage } from 'element-plus'

interface iProps {
  visible: boolean
  pwdProps: any
}
interface iEmits {
  (e: 'updateVisible', params: boolean): void
}
const props = withDefaults(defineProps<iProps>(), {
  visible: false
})
const emits = defineEmits<iEmits>()

const dialogVisible = ref(props.visible)

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  username: '', //账号
  password: '', //密码
  repassword: '' //确认密码
})
/* 验证确认密码 */
const equalToPassword = (rule, value, callback) => {
  if (ruleForm.password !== value) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}
const rules = reactive<FormRules>({
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    },
    { min: 6, max: 20, message: '密码长度最小6位，最大20位', trigger: 'blur' },
    {
      trigger: 'blur',
      validator: (rule, value, callback) => {
        var passwordreg = /(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\W])/
        if (!passwordreg.test(value)) {
          callback(new Error('密码必须含数字、字母和特殊符号，最小6位，最大20位'))
        }else{
          callback()
        }
      } 
    }
  ],
  repassword: [
    { required: true, message: '确认密码不能为空', trigger: 'blur' },
    { required: true, validator: equalToPassword, trigger: 'blur' }
  ]
})

// 关闭弹框
const closeDialog = () => {
  emits('updateVisible', false)
}
watch(
  () => props.visible,
  (newVal) => {
    dialogVisible.value = newVal
  }
)
const handleClose = (done: () => void) => {
  emits('updateVisible', false)
}
const confirmClick = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let userId = props.pwdProps.id
      let password = ruleForm.password
      changePasswordApi(userId, password)
        .then((val) => {
          if (val.code == 200 && val.success) {
            ElMessage.success('密码修改成功')
            closeDialog()
          } else {
            ElMessage.success(`密码修改失败,${val.message}`)
          }
        })
        .catch((err) => {
          ElMessage.success(`密码修改失败,${err.message}`)
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}
onMounted(() => {
  ruleForm.username = props.pwdProps.username
})
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    title="重新设定密码"
    width="30%"
    :before-close="handleClose"
    :destroy-on-close="true"
  >
    <el-form
      label-width="100px"
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      style="max-width: 500px"
    >
      <el-form-item label="用户账号">
        <el-input v-model="ruleForm.username" :disabled="true" />
      </el-form-item>
      <el-form-item label="登录密码" prop="password">
        <el-input v-model="ruleForm.password" />
      </el-form-item>
      <el-form-item label="确认密码" prop="repassword">
        <el-input v-model="ruleForm.repassword" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="confirmClick(ruleFormRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<style lang="less" scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
